<?php
/*
	Copyright (C)  2011  Bledar Leka.
    Permission is granted to copy, distribute and/or modify this document
    under the terms of the GNU Free Documentation License, Version 1.3
    or any later version published by the Free Software Foundation;
    with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
    A copy of the license is included in the section entitled "Code License".
	
	CacherMan 1.0 - PHP utility for autogenerating cached web contents !
	Developed by B.Leka (leka.al[at]gmail.com) 
	Usage : include the class on the top of your files, create a folder where to store cached files and chmod it 777!
*/

class CacherMan {
	public function __construct() {
		if (!isset($_POST['cacherman'])) {
			$this->cache_path 		= "cache";	#cached files stored directory name
			$this->page				= $_SERVER['REQUEST_URI'];
			$this->host				= $_SERVER['HTTP_HOST'];
			$this->extension		= ".txt"; 	# extension for the cached content
			$this->FileX			= $this->normalizeFile();
			$this->exclude			= array("/","/index.php"); #exlude urls and files from caching. Ex = array("/index.php","/my-other-url.html","/my/category/style/")
			$this->FullPath			= $this->cache_path."/".$this->FileX;
			$this->current_time		= time();
			$this->recache_after	= 420; # The cached file will live for this time,
			$this->NormalizeUrl();
			$this->StartCache();
		}
	}
	
	public function StartCache(){
		
		if (!in_array($this->page,$this->exclude)) {
		
			if (!file_exists($this->FullPath)) {
				$this->CachePage();
			} 
			else {
				if ($this->isUptoDate()==1) {
					include_once($this->FullPath);
					exit;
				} else {
					$this->CachePage();
				}
			}
		}
	}
	
	public function isUptoDate(){
		
		$content = file_get_contents($this->FullPath);
		if (!preg_match('@CacherX(.*)XrehcaC@siU',$content,$o)) {
			// the cacherman tag not present, so just recache the page puting our tag !
			return 0;
		} else {
			$old_time = $o[1];
			$time_diff = ($this->current_time - $old_time)/60;
			if ($time_diff>=$this->recache_after) {
				return 0;
			} else {
				return 1;
			}
		}
	}
	
	public function normalizeFile(){
		$s = iconv("UTF-8", "ASCII//TRANSLIT", $this->page);
		$s = strtolower($s);
		$s = preg_replace('@[^a-z 0-9]+@siU', ' ', $s);
		$s = str_replace(' ', '-', $s);
		$s = preg_replace('/-+/', "-", $s);
		return $s.$this->extension;
	}
	
	public function CachePage(){
		
		
		$this->headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
		$this->headers[] = 'Connection: Keep-Alive';
		$this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
		$this->user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
		$process = curl_init($this->URL);
		curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
		curl_setopt($process, CURLOPT_HEADER, 0);
		curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
		curl_setopt($process, CURLOPT_TIMEOUT, 30);
		curl_setopt($process, CURLOPT_POSTFIELDS, "cacherman=1");
		curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($process, CURLOPT_POST, 1);		
		$return = curl_exec($process);
		
		$output = $return;
		#let's do some small compressions
		$output = str_replace("\r","",$output);
		$output = str_replace("\n","",$output);
		$output = str_replace("\n\r","",$output);
		$output = str_replace("\s*","",$output);
		$output = str_replace(">
		",">",$output);
		$output = str_replace("         ","",$output);
		$output = str_replace("	 ","",$output);
		$output = str_replace("		","",$output);
		$output .= "<!--CacherX".$this->current_time."XrehcaC-->";
		$handle = fopen($this->FullPath,"wb");
		fwrite($handle,$output);
		fclose($handle);

	}
	
	public function NormalizeUrl(){
		if (!preg_match('@^(?:http://)?([^/]+)@i',$this->page,$o)) {
			$this->URL = "http://".$_SERVER['HTTP_HOST'].$this->page;
		} else {
			$this->URL = $this->page;
		}
	}
}
$cahe = new CacherMan;
?>